import React, { useState, useEffect, useRef } from 'react';
import jsPreviewDocx from '@js-preview/docx';
import jsPreviewExcel from '@js-preview/excel';
import jsPreviewPdf from '@js-preview/pdf';
import '@js-preview/excel/lib/index.css';
import '@js-preview/docx/lib/index.css';
import { Typography } from 'antd';
const { Paragraph } = Typography;
import { CopyOutlined } from '@ant-design/icons';

function OfficePreview({ url, type, name }) {
  const domref = useRef();

  useEffect(() => {
    if (!domref?.current) return;
    const jsPreview =
      type === 'word'
        ? jsPreviewDocx
        : type === 'xlsx'
        ? jsPreviewExcel
        : type === 'pdf'
        ? jsPreviewPdf
        : null;

    if (!jsPreview) {
      return;
    }

    //初始化时指明要挂载的父元素Dom节点
    const myPreviewer = jsPreview.init(domref?.current);

    //传递要预览的文件地址即可
    myPreviewer
      .preview(url)
      .then((res) => {
        console.log('预览完成');
      })
      .catch((e) => {
        console.log('预览失败', e);
      });
  }, [url, type, domref]);

  return (
    <div
      style={{
        width: 'calc(100vw - 80px)',
        height: 'calc( 100vh - 180px )',
        overflow: 'hidden',
      }}
    >
      {['word', 'xlsx', 'pdf'].includes(type) ? (
        <div
          ref={domref}
          style={{ width: '100%', height: '100%', overflow: 'auto' }}
        />
      ) : (
        <div className="center">
          无法在线预览的文件格式,{' '}
          <Paragraph
            copyable={{
              text: 'http://wbnoa.wbnacc.com/' + url,
              icon: <CopyOutlined />,
            }}
          />
        </div>
      )}
    </div>
  );
}
/*
 * @Author: wuhao930406 1148547900@qq.com
 * @Date: 2023-11-06 14:01:38
 * @LastEditors: wuhao930406 1148547900@qq.com
 * @LastEditTime: 2023-11-06 14:03:12
 * @FilePath: /wbn/src/components/CompanyName/components/txtviewer.jsx
 * @Description:
 *
 * Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
 */

function RemoteTxtFilePreview({ url }) {
  const [fileContent, setFileContent] = useState('');
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch(url)
      .then((response) => {
        return response?.text?.() ?? '无法加载...';
      })
      .then((data) => {
        setFileContent(data);
      })
      .catch((error) => {
        setError('资源无法加载...');
      });
  }, [url]);

  return <div>{error ? <div>{error}</div> : <pre>{fileContent}</pre>}</div>;
}

export { OfficePreview, RemoteTxtFilePreview };
